import renders from "./previewRender.js";

// 将文件对象转换为ArrayBuffer实例
export async function readBuffer(file){
    return new Promise((resolve,reject)=>{
        const reader=new FileReader();
        reader.onload=(e)=>{
            return resolve(e.target.result);
        };
        reader.onerror=(e)=>{
            return reject(e);
        };
        reader.readAsArrayBuffer(file);
    });
};

// 将buffer实例转换成base64编码
export async function readDataURL(buffer){
    return new Promise((resolve,reject)=>{
        const reader=new FileReader();
        reader.onload=(e)=>{
            return resolve(e.target.result);
        };
        reader.onerror=(e)=>{
            return reject(e);
        };
        reader.readAsDataURL(new Blob([buffer]));
    });
};

// 将buffer实例转换成文件内容的文本字符串
export async function readText(buffer){
    return new Promise((resolve,reject)=>{
        const reader=new FileReader();
        reader.onload=(e)=>{
            return resolve(e.target.result);
        };
        reader.onerror=(e)=>{
            return reject(e);
        };
        reader.readAsText(new Blob([buffer]),"utf-8");
    });
};

// 触发渲染效果
export async function render(buffer,type,target){
    const handler=renders[type];
    if(handler){
        return handler(buffer,target);
    }else{
        return renders.error(buffer,target,type);
    };
};